﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Marta.buchalska.wesele.DataModel;

namespace Marta.buchalska.wesele.Admin
{
    public partial class GalleryEdit : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (Request.QueryString["gid"] == null)
                Response.Redirect("~/Admin/PhotoGallery.aspx");
        }

        protected void newPhoto_ItemInserting(object sender, DetailsViewInsertEventArgs e)
        {
            DetailsView dv = (DetailsView)sender;
            FileUpload file = (FileUpload)dv.FindControl("photoFile");
            DataModel.WeedingDBDataContext context = new DataModel.WeedingDBDataContext();
            var gid = int.Parse(Request.QueryString["gid"]);

            Photo_gallery pg = context.Photo_galleries.FirstOrDefault(d => d.ID == gid);
            file.SaveAs(Server.MapPath("~/img/" + pg.Name + "/" + file.FileName));
            e.Values["URL"] = "~/img/" + pg.Name + "/" + file.FileName;
            e.Values["Photo_gallery_id"] = gid;
            e.Values["Name"] = file.FileName;

        }

        protected void Unnamed2_DeleteCommand(object source, DataListCommandEventArgs e)
        {
            var photoID = int.Parse(e.CommandArgument.ToString());
            wesele.DataModel.WeedingDBDataContext context = new WeedingDBDataContext();
            var photo = context.Photos.FirstOrDefault(d => d.ID == photoID);
            System.IO.File.Delete(Server.MapPath(photo.URL));
            context.Photos.DeleteOnSubmit(photo);
            context.SubmitChanges();
        }

        protected void btnDelGallery_Click(object sender, EventArgs e)
        {
            DataModel.WeedingDBDataContext context = new WeedingDBDataContext();
            int galleryID = int.Parse(Request.QueryString["gid"]);
            DataModel.Photo_gallery gallery = context.Photo_galleries.FirstOrDefault(d => d.ID == galleryID);
            context.Photos.DeleteAllOnSubmit(gallery.Photos);
            context.Photo_galleries.DeleteOnSubmit(gallery);

            FileMeneger meneger = new FileMeneger();

            meneger.DeleteGallery(Server.MapPath("~/img/" + gallery.Name));
            context.SubmitChanges();
            Response.Redirect("~/Admin/PhotoGallery.aspx");
        }
    }
}